#include "widget.h"
#include "ui_widget.h"

#include <QtXlsx/QtXlsx>
#include <QString>
#include <QLineEdit>
#include <fstream>
#include <iostream>
#include <string>
#include <QProcess>
#include <QPushButton>
#include  <QComboBox>
#include <QDebug>
#include <QFile>
#include <string>
#include <vector>
#include <QDateTime>
#include <QTime>
#include <QObject>
#include <QFileDialog>
#include <QLabel>
#include <string>
#include <QStringList>
#include <QMap>

QStringList getAllTableContents(QTableWidget* tableWidget) {
    QStringList allContents;
    int rowCount = tableWidget->rowCount();
    int columnCount = tableWidget->columnCount();

    for (int row = 0; row < rowCount; ++row) {
        QStringList rowContents;
        for (int col = 0; col < columnCount; ++col) {
            QTableWidgetItem* item = tableWidget->item(row, col);
            QString cellContent = item ? item->text() : QString();
            if(cellContent !="")
            rowContents.append(cellContent);
        }
        allContents.append(rowContents);
    }

    qDebug()<<"allContents"<<allContents;
    return allContents;
}
void tablesort(QTableWidget*& tableWidget,QStringList& str)
{
    tableWidget->clear();
    tableWidget->setHorizontalHeaderLabels(QStringList() << "文件名");
    int row = 0;
    int i = str.size()-1;
    while(row <str.size())
    {
        tableWidget->setItem(row,0,new QTableWidgetItem(str[i--].toStdString().c_str()));
        row++;
    }
}
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //串口1 被动发参数回复指令

    //foreach  就是范围for
    foreach(QSerialPortInfo info,QSerialPortInfo::availablePorts())
    {
        serialportinfo<<info.portName();
    }
    //myPort1 这个是串口通信的类
    myPort1 = new QSerialPort(this);
    ui->comboBox->addItem("选择设备");
    ui->comboBox->addItems(serialportinfo);
    //ui->comboBox->->setAlignment(Qt::AlignCenter);

    ui->tableWidget_PDF->setRowCount(10);
    ui->tableWidget_PDF->setColumnCount(1);
    ui->tableWidget_txt->setRowCount(10);
    ui->tableWidget_txt->setColumnCount(1);

    transtxt();
    trans();
    QByteArray byteArray;
    QString hexStr;
    hexStr = GBKtoCHAN("B6D4CFBA");
    handler();

    transtxt();
    QStringList str = getAllTableContents(ui->tableWidget_txt);

    tablesort(ui->tableWidget_txt,str);

}
void Widget::transtxt()
{
    ui->tableWidget_txt->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_txt->clear(); // 清除旧数据

    QDir dir(directoryPath); // 替换为你的文件夹路径
    QFileInfoList fileList = dir.entryInfoList(QStringList() << "*.txt");
    // 根据最后修改时间降序排序
    std::sort(fileList.begin(), fileList.end(), [](const QFileInfo &a, const QFileInfo &b) {
        return a.lastModified() > b.lastModified();
    });
    int rowCount = 0;
    for(auto fileInfo:fileList)
    {
        //输出文件名包含后缀
        //        qDebug() << fileInfo.fileName();
        //输出文件的完整路径名
        //qDebug() << fileInfo.absoluteFilePath();
        ui->tableWidget_txt->insertRow(rowCount);

        //插入文件名列
        QTableWidgetItem *itemFileName = new QTableWidgetItem(fileInfo.fileName());
        //        qDebug()<<itemFileName;
        ui->tableWidget_txt->setItem(rowCount, 0, itemFileName); // 假设文件名是第二列

        rowCount++;
    }

    // 设置列标题（如果需要）
    ui->tableWidget_txt->setHorizontalHeaderLabels(QStringList() << "文件名");
}

void Widget::trans()
{
    ui->tableWidget_PDF->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget_PDF->clear(); // 清除旧数据
    QDir dir(".\\PDF_dir\\");              //为你的文件夹路径
    QFileInfoList fileList = dir.entryInfoList(QStringList() << "*.PDF");
    // 根据最后修改时间降序排序
    std::sort(fileList.begin(), fileList.end(), [](const QFileInfo &a, const QFileInfo &b) {
        return a.lastModified() > b.lastModified();
    });
    int rowCount = 0;
    for(auto fileInfo:fileList)
    {
        ui->tableWidget_PDF->insertRow(rowCount);

        //插入文件名列
        QTableWidgetItem *itemFileName = new QTableWidgetItem(fileInfo.fileName());
        ui->tableWidget_PDF->setItem(rowCount, 0, itemFileName); // 假设文件名是第二列
        rowCount++;
    }

    // 设置列标题（如果需要）
    ui->tableWidget_PDF->setHorizontalHeaderLabels(QStringList() << "历史生成的PDF文件名");

}

void Widget::handler()
{
    QFile file("./TXT/B.txt");
    file.open(QFile::ReadOnly);

    while(!file.atEnd())
    {
        QString line = file.readLine();

        QStringList linespilt = line.split("=");


        bingdu_map[linespilt[0]] = linespilt[1].left(linespilt[1].size()-2);
        //qDebug()<<bingdu_map[linespilt[0]];

    }
    file.close();
}

QString Widget::GBKtoCHAN(const QString &hexStr)
{
    QByteArray byteArray;
    // 假设hexStr是有效的16进制字符串，且每两个字符代表一个字节
    for (int i = 0; i < hexStr.size(); i += 2) {
        bool ok;
        uchar byte = static_cast<uchar>(hexStr.mid(i, 2).toInt(&ok, 16));
        if (ok) {
            byteArray.append(byte);
        }
    }
    // 使用GBK编码的QTextCodec来解码字节流为QString
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    if (!codec) {
        qWarning("GBK codec not found!");
        return QString();
    }
    return codec->toUnicode(byteArray);
}
Widget::~Widget()
{
    delete ui;
}
QString SetDate(int x)
{
    switch (x) {
    case 1:
        return "阳性";
        break;
    case 2:
        return "阴性";
        break;
    case 3:
        return "弱阳性";
        break;
    case 0:
        return "";
        break;
    default:
        return "检测异常";
        break;
    }
}

QFile file;
int ret = 1;
QString createFileNameWithDateTime(QString name) {
    // 获取当前日期和时间
    QDateTime now = QDateTime::currentDateTime();
    QDateTime currentTime = QDateTime::currentDateTime();
       // 将当前日期和时间转换为自纪元（1970-01-01T00:00:00Z）以来的秒数
    qint64 timestamp = currentTime.toSecsSinceEpoch();


    // 输出文件名以验证
    QString tmp = QString("检测报告%1_%2_%3.txt").arg(name).arg(timestamp).arg(ret++);
    //QString tmp = QString("检测报告%1").arg(fileName);

    // 返回文件名
    return tmp ;
}
QFile file1;
int  stat = 0;
int flag =0;
int current;
QByteArray tmp_1;

void Widget::Slot_ReadSerialPortData()
{
    QString strHex;//16进制数据
    QString str;
    QString teststr("");
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QString chineseText ;
    QByteArray temp=myPort1->readAll();
    QByteArray arr;
    if (!temp.isEmpty())
    {
        QDataStream out(&temp,QIODevice::ReadWrite);
        while (!out.atEnd())
        {
            qint8 outChar=0;
            out>>outChar;
            QString str1=QString("%1").arg(outChar&0xFF,2,16,QLatin1Char('0'));
            QString str2=QString("%1").arg(outChar&0xFF,2,10,QLatin1Char('0'));
            if (str1.length()>1)
            {
                strHex+=str1;
            }
            else
            {
                strHex+="0"+str1;
            }
        }
    }

    //去掉了头珍
    if(arr != nullptr)
    {
        tmp_1 =arr;
    }
    tmp_1 += temp;

    if(tmp_1.size() < 3)
    {

         tmp_1 = tmp_1.mid(1);

    }
     qDebug()<<"temp"<<temp;
    if(tmp_1.left(2) == "\xFD\xDF" )
    {
        int i = 0;
        while(tmp_1[i]!= ',')
        {
            if(tmp_1[i] == ' ')
            {
                tmp_1[i] ='_';
            }
            if(tmp_1[i]==':' )
            {
                tmp_1[i] = '_';
            }
            i++;
        }
        QString name;
        if( tmp_1.left(3) == "\x00\xFD\xDF")
        {

            chineseText = codec->toUnicode(tmp_1.mid(7,i-6));
            name = chineseText.toStdString().c_str();

        }
        else{
          chineseText = codec->toUnicode(tmp_1.mid(6,i-6));
          name = chineseText.toStdString().c_str();
        }
       // qDebug()<<"测试过"<<"i: "<<i;
        tmp_1 = tmp_1.mid(13);


        QString filename =  "./"+createFileNameWithDateTime(name);
       // qDebug()<<"成:"<<filename;
        file1.setFileName(filename);
        if(!file1.open(QFile::WriteOnly|QFile::Append))
        {
              qDebug()<<"打开失败";
        }
       // qDebug()<<"open:"<<filename;
       // flag =1;
    }

    int index =0;
    if(tmp_1.contains("\xFD\xDF"))
    {
        index= tmp_1.indexOf("\xFD\xDF");
        arr = tmp_1.mid(index);
        //拿去到第二个检测数据的针头之后的数据
    }


    if(tmp_1.contains("\xFE\xEF"))
    {
        chineseText = codec->toUnicode(tmp_1);

        file1.write(chineseText.toStdString().c_str());
        file1.close();
        chineseText = "";
        tmp_1 = "";

    }

}


void Widget::on_pushButton_clicked()
{
    myPort1->setPortName(ui->comboBox->currentText());
    if(ui->pushButton->text()=="打开设备")//打开串口
    {
        if(myPort1->open(QIODevice::ReadWrite))//读写方式打开,成功后设置串口
        {

            myPort1->setBaudRate(115200);//设置波特率
            myPort1->setDataBits(QSerialPort::Data8);//设置数据位
            myPort1->setParity(QSerialPort::NoParity);//设置校验位
            myPort1->setFlowControl(QSerialPort::NoFlowControl);//设置流控制
            myPort1->setStopBits(QSerialPort::OneStop);//设置停止位
            ui->pushButton->setText("关闭设备");
            ui->comboBox->setEnabled(false);//端口下拉框不可用
            qDebug()<<"串口打开成功";
            connect(myPort1,SIGNAL(readyRead()),this,SLOT(Slot_ReadSerialPortData()));
        }
        else//串口打开失败
        {
            qDebug()<<"串口打开失败";
            QMessageBox::about(NULL, "提示", "打开出错，串口被占用！");
            return ;
        }
    }
    else if(ui->pushButton->text()=="关闭设备")//关闭串口
    {
        ui->pushButton->setText("打开设备");
        myPort1->close();//关串口
        ui->comboBox->setEnabled(true);//端口下拉框可用
        qDebug()<<"串口关闭";
    }
}
void renameFile(const QString &oldName, const QString &newName)
{
    QFile file(oldName);

    // 检查文件是否存在
    if (!file.exists()) {
        qDebug() << "文件不存在：" << oldName;
        return;
    }
    // 尝试重命名文件
    bool success = file.rename(newName);

    if (success) {
        qDebug() << "文件重命名成功：" << oldName << " => " << newName;
    } else {
        qDebug() << "文件重命名失败：" << oldName << " => " << newName;
        // 在这里可以添加错误处理代码
    }
}
void Widget::on_translate_PDF_clicked()
{
    QTime currenttime= QTime::currentTime();
    QDateTime curentdate = QDateTime::currentDateTime();



    QXlsx::Document test_Xlsx(".\\PDF_dir\\test.xlsx");
    QXlsx::Format format;
    //载入上方信息栏
    QString title = QString ("    %1水产服务中心病原%2项核酸检测报告").arg(ui->name_line->text()).arg(ui->line_name->text());

    ui->label_9->setText(title);
    ui->label_9->setAlignment(Qt::AlignCenter);




    test_Xlsx.write("A1",title);
    test_Xlsx.write("C5",ui->line_name->text());
    test_Xlsx.write("C7",ui->line_size->text());
    test_Xlsx.write("C9",ui->line_num->text());
    test_Xlsx.write("C11",ui->line_machine->text());

    test_Xlsx.write("F5",ui->line_kind->text());
    test_Xlsx.write("F7",ui->line_from->text());
    test_Xlsx.write("F9",ui->line_from_2->text());

    test_Xlsx.write("I5",ui->line_kind_2->text());
    test_Xlsx.write("I7",ui->line_kind_3->text());

    if(ui->line_kind_4->text() == nullptr)
        ui->line_kind_4->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("I9",ui->line_kind_4->text());

    if(ui->line_kind_5->text() == nullptr)
        ui->line_kind_5->setText(currenttime.toString("hh:mm:ss"));


    test_Xlsx.write("I11",ui->line_kind_5->text());
    if(ui->line_size_2->text() == nullptr)
        ui->line_size_2->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("B34",ui->line_size_2->text());
    test_Xlsx.write("F34",ui->line_size_3->text());

    test_Xlsx.write("I34",ui->line_size_4->text());


    //写入execl表 检测项目
    test_Xlsx.write("B18",ui->label_33->text());
    test_Xlsx.write("B19",ui->label_34->text());

    qDebug()<<(ui->label_33->text());
    qDebug()<<(ui->label_34->text());
    qDebug()<<(ui->label_35->text());
    qDebug()<<(ui->label_36->text());



    test_Xlsx.write("B20",ui->label_35->text());
    test_Xlsx.write("B21",ui->label_36->text());
    test_Xlsx.write("B22",ui->label_37->text());
    test_Xlsx.write("B23",ui->label_38->text());
    test_Xlsx.write("B24",ui->label_39->text());
    test_Xlsx.write("B25",ui->label_40->text());

    //写入execl表 检测结果

     qDebug()<<"||||测试是否进入";
    test_Xlsx.write("F18",ui->label_42->text());
    test_Xlsx.write("F19",ui->label_48->text());
    test_Xlsx.write("F20",ui->label_43->text());
    test_Xlsx.write("F21",ui->label_41->text());
    test_Xlsx.write("F22",ui->label_46->text());
    test_Xlsx.write("F23",ui->label_47->text());
    test_Xlsx.write("F24",ui->label_45->text());
    test_Xlsx.write("F25",ui->label_44->text());
    test_Xlsx.saveAs(".\\PDF_dir\\test.xlsx");

    qDebug()<<"保存成功";



    test_Xlsx.write("C5",ui->line_name->text());
    test_Xlsx.write("C7",ui->line_size->text());
    test_Xlsx.write("C11",ui->line_machine->text());

    test_Xlsx.write("F5",ui->line_kind->text());
    test_Xlsx.write("F7",ui->line_from->text());
    test_Xlsx.write("F9",ui->line_from_2->text());

    test_Xlsx.write("I5",ui->line_kind_2->text());
    test_Xlsx.write("I7",ui->line_kind_3->text());
    if(ui->line_kind_4->text() == nullptr)
        ui->line_kind_4->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("I9",ui->line_kind_4->text());

    if(ui->line_kind_5->text() == nullptr)
        ui->line_kind_5->setText(currenttime.toString("hh:mm:ss"));


    test_Xlsx.write("I11",ui->line_kind_5->text());
    if(ui->line_size_2->text() == nullptr)
        ui->line_size_2->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("B34",ui->line_size_2->text());
    test_Xlsx.write("F34",ui->line_size_3->text());

    test_Xlsx.write("I34",ui->line_size_4->text());



    qDebug()<<" Label 的值 "<<ui->label_48->text();


    test_Xlsx.saveAs(".\\PDF_dir\\test.xlsx");

    qDebug()<<"保存成功";
    //以上是写入excl表

    //execl  转  PDF
    ////////////////////////////////////////////////
    QString inputFile = ".\\PDF_dir\\test.xlsx";
    if(inputFile.isEmpty())
        return;

    QFile file(inputFile);
    if (!file.exists()) {
        qDebug() << "文件不存在：" << inputFile;
        return;
    }
    QDateTime dateTime = QDateTime::currentDateTime();
    QString pdfpath;
    if (inputFile.endsWith("xlsx", Qt::CaseInsensitive))
        pdfpath = inputFile.left(inputFile.lastIndexOf('.')) + ".pdf";
    else if (inputFile.endsWith("xls", Qt::CaseInsensitive))
        pdfpath = inputFile.left(inputFile.lastIndexOf('.')) + ".pdf";

    QProcess process;
    QString program = "C:\\Program Files\\LibreOffice\\program\\soffice.exe";
    QStringList arguments;
    arguments << "--headless"
              << "--convert-to" << "pdf"
              << "--outdir" << QDir::toNativeSeparators(QFileInfo(pdfpath).absolutePath())
              << QDir::toNativeSeparators(inputFile);
    QString customDateTimeString2 = dateTime.toString("dd-MM-yyyy hh-mm-ss");

    process.start(program, arguments);
    if (!process.waitForFinished()) {
        qDebug() << "转化的文件正在被占用";
    } else {
        int exitCode = process.exitCode();
        if (exitCode == 0) {
            qDebug() << "转化成功！.";

            // 重命名PDF文件（如果需要）
            qDebug()<<"pdfnaem:"<<pdfpath;
            QString newPdfPath = ".\\PDF_dir\\"+customDateTimeString2 + ".pdf";
            qDebug()<<"new name"<<newPdfPath;
            if (QFile::rename(pdfpath, newPdfPath)) {
                qDebug() << "PDF文件重命名成功：" << newPdfPath;
            } else {
                qDebug() << "PDF文件重命名失败";
            }
        } else {
            qDebug() << "转化失败（原因）：" << exitCode;
        }
    }
    QMessageBox::about(NULL, "提示", "PDF转化成功！请及时按刷新PDF");
}
//更改名字

void Widget::on_tableWidget_cellDoubleClicked(int row, int column)
{
    qDebug()<<ui->tableWidget_txt->item(row, column);
}

void Widget::on_pushButton_4_clicked()
{
    transtxt();
}

void Widget::on_pushButton_8_clicked()
{
    trans();
    QMessageBox::about(NULL, "提示", "PDF文本列表刷新成功！");
}

void Widget::on_test_pp_clicked()
{
    transtxt();
    QStringList str = getAllTableContents(ui->tableWidget_txt);

    tablesort(ui->tableWidget_txt,str);
    QMessageBox::about(NULL, "提示", "数据文本刷新成功,并且排序成功！");
}

void Widget::on_test_pp_2_clicked()
{
    trans();
}

void Widget::on_pushButton_6_clicked()
{
    ui->line_name->clear();
    ui->line_size->clear();
    ui->line_num->clear();
    ui->line_machine->clear();
    ui->line_kind->clear();
    ui->line_from->clear();
    ui->line_from_2->clear();
    ui->name_line->clear();
    ui->line_kind_3->clear();
    ui->line_kind_4->clear();
    ui->line_kind_5->clear();
    ui->line_kind_2->clear();
    //进行一个txt文件IO
    QString title ="";
    //qDebug()<<ui->tableWidget_txt->currentItem();

    if(ui->tableWidget_txt->currentItem() == nullptr)
    {
        QMessageBox::about(NULL, "提示", "暂时没有选择对应的txt文件，没有数据载入！");
        return;
    }

    QTableWidgetItem* cur = ui->tableWidget_txt->currentItem();
    //qDebug()<<"cur: "<<cur->text();
    QString path = "./" + cur->text() ;


    QFile file(path.toStdString().c_str());
    QString line;
    QStringList strlist;
    int ret = 0;
    file.open(QFile::ReadOnly);
    QString str_1;
    while (1)
    {
        if(ret == 0)
        {
            QString tmp = file.readLine();
            if(tmp == nullptr)
            {
                QMessageBox::critical(this,"警告！","文件为空");
                return;
            }
            QStringList list = tmp.split(";");
            int i =0;

            while(tmp[i] != ',')
            {
                title +=tmp[i];
                i++;
            }
            i++;
            while(tmp[i] == " " || tmp[i] != ";")
            {
              i++;
            }
            if(tmp[i]==";")
            str_1 = tmp.mid(i+1);
            else
            {
                str_1 = tmp.mid(i);
            }
            ret++;
        }
        else
        {
            QString str = str_1;
            qDebug()<<"Str: "<<str;
            str+= file.readAll();
            strlist = str.split(";");
            break;
        }
    }
    //检测项目
    QString title1 = QString ("%1水产服务中心病原%2项核酸检测报告").arg(ui->name_line->text()).arg(ui->line_name->text());
    ui->label_9->setText(title1);
    ui->label_9->setAlignment(Qt::AlignCenter);

    if(strlist.empty())
    {
        QMessageBox::about(NULL, "提示", "该文件暂时没有数据！");
        return;
    }

    if(strlist.length() >=1)
    {
        QStringList str_list = strlist[0].split("/");

        ui->label_33->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }
    if(strlist.length() >=2)
    {
        QStringList str_list = strlist[1].split("/");
        ui->label_34->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }

    if(strlist.length() >=3)
    {
        QStringList str_list = strlist[2].split("/");
        ui->label_35->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }
    if(strlist.length() >=4)
    {
        QStringList str_list = strlist[3].split("/");
        ui->label_36->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }

    if(strlist.length() >=5)
    {

        QStringList str_list = strlist[4].split("/");
        ui->label_37->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);


    }
    if(strlist.length() >=6)
    {
        QStringList str_list = strlist[5].split("/");
        ui->label_38->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }
    if(strlist.length() >=7)
    {
        QStringList str_list = strlist[6].split("/");
        ui->label_39->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }

    if(strlist.length() >=8)
    {
        QStringList str_list = strlist[7].split("/");
        ui->label_40->setText(str_list[0]+"/"+bingdu_map[str_list[1]]);
    }
    if(strlist.length() >=9)
    {
         ui->label_42->setAlignment(Qt::AlignCenter);
         ui->label_42->setText(SetDate(strlist[8].toInt()));
    }
    if(strlist.length() >=10)
    {
        ui->label_48->setAlignment(Qt::AlignCenter);
        ui->label_48->setText(SetDate(strlist[9].toInt()));
    }

    if(strlist.length() >=11)
    {
        ui->label_43->setAlignment(Qt::AlignCenter);
        ui->label_43->setText(SetDate(strlist[10].toInt()));
    }

    if(strlist.length() >=12)
    {
         ui->label_41->setAlignment(Qt::AlignCenter);
        ui->label_41->setText(SetDate(strlist[11].toInt()));
    }

    if(strlist.length() >=13)
    {
         ui->label_46->setAlignment(Qt::AlignCenter);
         ui->label_46->setText(SetDate(strlist[12].toInt()));

    }

    if(strlist.length() >=14)
    {
        ui->label_47->setAlignment(Qt::AlignCenter);
        ui->label_47->setText(SetDate(strlist[13].toInt()));
    }

    if(strlist.length() >=15)
    {
        ui->label_45->setAlignment(Qt::AlignCenter);
        ui->label_45->setText(SetDate(strlist[14].toInt()));
    }
    if(strlist.length() >=16)
    {
        ui->label_44->setAlignment(Qt::AlignCenter);
        ui->label_44->setText(SetDate(strlist[15].toInt()));
    }
    QMessageBox::about(NULL, "提示", "数据载入成功！");
    file.close();

}
void Widget::on_test_excl_clicked()
{
    QTime currenttime= QTime::currentTime();
    QDateTime curentdate = QDateTime::currentDateTime();

    QXlsx::Document test_Xlsx("C:/Users/ZC-Hyx/Desktop/test.xlsx");
    qDebug()<<"打开文件";
    qDebug()<<"开始写入";

    test_Xlsx.write("C5",ui->line_name->text());
    test_Xlsx.write("C7",ui->line_size->text());
    test_Xlsx.write("C11",ui->line_machine->text());

    test_Xlsx.write("G5",ui->line_kind->text());
    test_Xlsx.write("G7",ui->line_from->text());
    test_Xlsx.write("G9",ui->line_from_2->text());
    test_Xlsx.write("J5",ui->line_kind_2->text());
    test_Xlsx.write("J7",ui->line_kind_3->text());
    if(ui->line_kind_4->text() == nullptr)
        ui->line_kind_4->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("J9",ui->line_kind_4->text());

    if(ui->line_kind_5->text() == nullptr)
        ui->line_kind_5->setText(currenttime.toString("hh:mm:ss"));


    test_Xlsx.write("J11",ui->line_kind_5->text());
    if(ui->line_size_2->text() == nullptr)
        ui->line_size_2->setText(curentdate.toString("yyyy-MM-dd"));

    test_Xlsx.write("B34",ui->line_size_2->text());
    test_Xlsx.write("F34",ui->line_size_3->text());

    test_Xlsx.write("I34",ui->line_size_4->text());


    qDebug()<<" Label 的值 "<<ui->label_48->text();
    //写入execl表 检测项目
    test_Xlsx.write("B18",ui->label_48->text());
    test_Xlsx.write("B19",ui->label_42->text());
    test_Xlsx.write("B20",ui->label_43->text());

    //写入execl表 检测结果
    test_Xlsx.write("G18",ui->label_48->text());
    test_Xlsx.write("G19",ui->label_42->text());
    test_Xlsx.write("G20",ui->label_43->text());

    test_Xlsx.saveAs("C:/Users/ZC-Hyx/Desktop/test.xlsx");
    qDebug()<<"保存成功";
}

void deletePdfFilesInCurrentDirectory1() {
    QString pat = "./PDF_dir/";
    QDir dir(pat);

    // 获取当前目录中所有的文件信息列表
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);

    // 遍历文件信息列表，查找并删除 .txt 文件
    for (const QFileInfo &fileInfo : fileList) {
        if (fileInfo.suffix() == "pdf") {
            QFile file(fileInfo.absoluteFilePath());
            if (file.remove()) {
                qDebug() << "Deleted file:" << fileInfo.fileName();
            } else {
                qWarning() << "Failed to delete file:" << fileInfo.fileName();
            }
        }
    }
}
void Widget::on_pushButton_5_clicked()
{

    deletePdfFilesInCurrentDirectory1();
    trans();
    QMessageBox::about(NULL, "提示", "文件删除成功！");
}
void Widget::on_tableWidget_PDF_cellDoubleClicked()
{
    QTableWidgetItem* cur = ui->tableWidget_PDF->currentItem();
    QString inputFile = ".\\"+cur->text();
    //
    QString path = inputFile;
    QProcess * proc = new QProcess();
    proc->startDetached("cmd.exe",QStringList()<<"/c"<<path);
}
void Widget::on_pushButton_3_clicked()
{
    myPort1->write("S");
    ret =0;
    transtxt();

}
void Widget::on_openfile_clicked()
{
    QTableWidgetItem* cur = ui->tableWidget_PDF->currentItem();
    if(cur == nullptr)
    {
        QMessageBox::warning(this,"提示","未选择可打开的文件");
        return ;
    }
    QString path = "./PDF_dir/" + cur->text(); // 确保这里cur不为nullptr且cur->text()是有效的PDF文件路径

    QUrl url(QUrl::fromLocalFile(path));

    QDesktopServices::openUrl(url);

}


void Widget::on_close_clicked()
{
    this->close();
}

void Widget::on_pushButton_2_clicked()
{
    serialportinfo.clear();
    ui->comboBox->clear();
    foreach(QSerialPortInfo info,QSerialPortInfo::availablePorts())
    {
        serialportinfo<<info.portName();
    }
    ui->comboBox->addItems(serialportinfo);


    QMessageBox::about(NULL, "提示", "串口刷新成功,请查看COMBOX");
}

void deleteTxtFilesInCurrentDirectory() {
    QDir dir(QDir::currentPath());

    // 获取当前目录中所有的文件信息列表
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);

    // 遍历文件信息列表，查找并删除 .txt 文件
    for (const QFileInfo &fileInfo : fileList) {
        if (fileInfo.suffix() == "txt") {
            QFile file(fileInfo.absoluteFilePath());
            if (file.remove()) {
                qDebug() << "Deleted file:" << fileInfo.fileName();
            } else {
                qWarning() << "Failed to delete file:" << fileInfo.fileName();
            }
        }
    }
}


void Widget::on_pushButton_delete_clicked()
{
    deleteTxtFilesInCurrentDirectory();
    transtxt();
    QMessageBox::about(NULL, "提示", "文件删除成功！");
}
